<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 导入axios包 -->
    <script src="./node_modules/axios/dist/axios.min.js"></script>
    <style>
      body {
        margin: 0;
        padding: 30px;
      }
    </style>
  </head>
  <body>
    <h1>修改用户</h1>

    <label for="username">用户名:</label>
    <input type="text" id="username" />
    <br />

    <label for="password">密码:</label>
    <input type="text" id="password" />
    <br />

    <button>提交</button>

    <script>
      //获取从index.html页面携带过滤的id的值
      //  console.log(location)//发现href和search属性中都有id的值
      //  console.log(location.search)//?id=1
      //  console.log(location.search.replace('?',''))//id=1
      //  console.log(location.search.replace('?','').split('='))//['id', '1']
      //  console.log(location.search.replace('?','').split('=')[1])//1

      //方式一:手动获取id的值
      //const id = location.search.replace('?','').split('=')[1]
      //console.log(id)

      //方式二:通过URLSearchParams对象获取
      const id = new URLSearchParams(location.search).get('id')
      console.log(id)

      //发送axios的get请求,获取要修改用户的数据,进行回显操作
      axios.get(`http://localhost:3000/users/${id}`).then((res) => {
        const user = res.data
        console.log(user)

        //回显操作
        document.querySelector('#username').value = user.username
        document.querySelector('#password').value = user.password
      })

      //获取提交按钮,监听点击事件
      document.querySelector('button').addEventListener('click', function () {
        //获取用户名和密码
        const username = document.querySelector('#username').value
        const password = document.querySelector('#password').value

        //发送put请求
        axios({
          url: `http://localhost:3000/users/${id}`,
          method: 'put',
          data: { username: username, password: password },
        }).then(
          //跳转到首页
          (location.href = './index.html')
        )
      })
    </script>
  </body>
</html>
